<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Groovy,">










<meta name="description" content="DSL：领域特定语言。常用于聚焦指定的领域或问题，这就要求 DSL 具备强大的表现力，同时在使用起来要简单。由于其使用简单的特性，DSL 通常不会像 Java，C++等语言将其应用于一般性的编程任务。 由语言的难易程度，做一个简单的排序：配置文件 &amp;lt; DSL &amp;lt; 编程语言(eg:Java,C++…)  配置文件是最简单的一种，常见的有用 xml 来进行配置项目，这需要预先定义好一些规范">
<meta name="keywords" content="Groovy">
<meta property="og:type" content="article">
<meta property="og:title" content="Groovy与DSL">
<meta property="og:url" content="https://zachaxy.github.io/2017/12/13/Groovy与DSL/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="DSL：领域特定语言。常用于聚焦指定的领域或问题，这就要求 DSL 具备强大的表现力，同时在使用起来要简单。由于其使用简单的特性，DSL 通常不会像 Java，C++等语言将其应用于一般性的编程任务。 由语言的难易程度，做一个简单的排序：配置文件 &amp;lt; DSL &amp;lt; 编程语言(eg:Java,C++…)  配置文件是最简单的一种，常见的有用 xml 来进行配置项目，这需要预先定义好一些规范">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.294Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Groovy与DSL">
<meta name="twitter:description" content="DSL：领域特定语言。常用于聚焦指定的领域或问题，这就要求 DSL 具备强大的表现力，同时在使用起来要简单。由于其使用简单的特性，DSL 通常不会像 Java，C++等语言将其应用于一般性的编程任务。 由语言的难易程度，做一个简单的排序：配置文件 &amp;lt; DSL &amp;lt; 编程语言(eg:Java,C++…)  配置文件是最简单的一种，常见的有用 xml 来进行配置项目，这需要预先定义好一些规范">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/12/13/Groovy与DSL/">





  <title>Groovy与DSL | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/12/13/Groovy与DSL/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">Groovy与DSL</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-13T10:33:46+08:00">
                2017-12-13
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,857
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <p>DSL：领域特定语言。常用于聚焦指定的领域或问题，这就要求 DSL 具备强大的表现力，同时在使用起来要简单。由于其使用简单的特性，DSL 通常不会像 Java，C++等语言将其应用于一般性的编程任务。</p>
<p>由语言的难易程度，做一个简单的排序：配置文件 &lt; DSL &lt; 编程语言(eg:Java,C++…)</p>
<ul>
<li>配置文件是最简单的一种，常见的有用 xml 来进行配置项目，这需要预先定义好一些规范，只有按照预先定义好的规范书写配置文件，才能得到正确的解析。解析其实也是使用编程语言，通过读文件的形式，按照预先定义的规范，得到相应的配置。</li>
<li>编程语言是最高级的，其本身可以实现条件判断，循环等这样的逻辑，这是配置文件很难实现的。但是很少有用编程语言来直接表述一项任务的，因为其缺乏像配置文件那样简介的语义。</li>
<li>DSL 则介于两者之间，即有像配置文件那样清晰的语义，即很强的语义表现力，同时自身也具备一定的逻辑。</li>
</ul>
<p>然而 DSL 的应用领域非常有限，没有必要单独为其开发一款语言。就像 xml 中的配置文件是通过高级语言解析而来，我们也可以用高级语言解析 DSL 文件，执行相关的逻辑。但是与 xml 配置文件不同的是，xml 配置文件需要预先定义规范。而 DSL 不需要定义规范，其语法受到现有语言的约束，不用使用任何解析器，而是巧妙的讲语法映射到底层语言中的方法和属性，这样使得用户在使用起来可能意识不到自己正在使用的是一门更广泛的语言的语法。</p>
<p>DSL 的两个显著特点：</p>
<ul>
<li>上下文相关</li>
<li>流畅的调用</li>
</ul>
<p>鉴于 Groovy 动态特性和元编程能力，其很适合作为 DSL 底层的解析语言。接下来探讨在 Groovy 的基础上构建 DSL。</p>
<p>对于 Groovy 来说，一个伟大的 DSL 产物就是新一代构建工具——Gradle。</p>
<a id="more"></a>

<h1 id="利用闭包实现上下文相关性"><a href="#利用闭包实现上下文相关性" class="headerlink" title="利用闭包实现上下文相关性"></a>利用闭包实现上下文相关性</h1><p>上下文：就是一个特定的语境，在这个语境下，大家没有必要一直重申这一语境前提，而是所有的逻辑都在这个前提下执行。<br>看如下 Groovy 代码：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">list = [<span class="number">1</span>,<span class="number">2</span>]</span><br><span class="line">list.add(<span class="number">3</span>)</span><br><span class="line">list.add(<span class="number">4</span>)</span><br><span class="line">println list.size()</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，每条语句都是针对 list 的，但是每条语句都重复声明了 list 的语境，未免有些啰嗦，于是 groovy 提供了 with()方法，用来设置上下文，上面的代码可以修改为：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">list = [<span class="number">1</span>,<span class="number">2</span>]</span><br><span class="line">list.with&#123;</span><br><span class="line">	add(<span class="number">3</span>)</span><br><span class="line">	add(<span class="number">4</span>)</span><br><span class="line">	println size()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里使用了闭包，将闭包中的语句的上下文路由到 list。原因是 with 中的闭包将其 delegate 设置到了调用 with 的对象上。</p>
<p>同时注意到这里 with 的原型是 <code>with(closure)</code>，当一个方法的最后一个参数是闭包，同时我们传入的是一个匿名闭包时，那么其调用的方式就是上述 with 的形式，这不是方法的定义，而是方法的调用，只不过后面的闭包是作为方法的最后一个参数，单独拿出来了。单独拿出来比写在括号内，语法更加简洁。因为花括号后面在跟一个右括号总感觉破坏了代码的优美性。</p>
<p>受到 Groovy 所提供的 with 的启发，我们也可以仿照 with 的实现方式，提供类似的上下文执行环境，实现我们的 DSL。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> addList(closure)&#123;</span><br><span class="line">	list = []</span><br><span class="line">	closure.delegate = list</span><br><span class="line">	closure()</span><br><span class="line">	list</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用 addList 提供的上下文特性，想 list 中添加元素</span></span><br><span class="line">list = addList()&#123;</span><br><span class="line">    add(<span class="number">1</span>)</span><br><span class="line">    add(<span class="number">2</span>)</span><br><span class="line">    add(<span class="number">3</span>)</span><br><span class="line">    size()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">println list</span><br></pre></td></tr></table></figure>

<p>通过将闭包的代理进行配置，自然就提供了一个统一的上下文环境，这样我们在闭包中调用的任何方法，都是基于之前设置的代理的，这一方法在 gradle 中是很常见的。</p>
<h1 id="Groovy-针对流畅性的先天优势"><a href="#Groovy-针对流畅性的先天优势" class="headerlink" title="Groovy 针对流畅性的先天优势"></a>Groovy 针对流畅性的先天优势</h1><p>流畅性可以提高代码的可读性，使代码自然流动。</p>
<p>Groovy 所具备的天然的优势有：</p>
<ul>
<li>动态类型和可选类型</li>
<li>动态加载，操作和执行脚本的灵活性</li>
<li>分类和 ExpandoMetaClass 可以扩展已有类的功能</li>
<li>闭包为执行提供很好的上下文</li>
<li>操作符的重载可以使我们自由的定义操作符</li>
</ul>
<h2 id="灵活的方法调用语法"><a href="#灵活的方法调用语法" class="headerlink" title="灵活的方法调用语法"></a>灵活的方法调用语法</h2><p>如果方法是<strong>有返回值</strong>的，那么在调用时可以不使用点符号(.) 而是用空格将调用者和方法分开，就能在返回的这个实例上进行连续的调用</p>
<h2 id="灵活的括号语法"><a href="#灵活的括号语法" class="headerlink" title="灵活的括号语法"></a>灵活的括号语法</h2><p>当调用的方法需要参数时，Groovy 不要求使用括号，若有多个参数，那么参数之间依然使用逗号分隔；如果不需要参数，那么方法的调用必须显示的使用括号。</p>
<h2 id="让无参数的方法调用也不需要括号"><a href="#让无参数的方法调用也不需要括号" class="headerlink" title="让无参数的方法调用也不需要括号"></a>让无参数的方法调用也不需要括号</h2><p>为了和有参数的方法调用时不使用括号的语法，统一风格，我们设法让无参数的方法调用也不需要括号。当然这个功能是 Groovy 自身不支持的。直接这样调用，Groovy 会认为这是在访问一个属性，那么我们结合 Groovy 中对属性的访问就是对 getXXX 的访问，将无参数的方法名改成 getXXX 的形式，即可实现“调用无参数的方法不需要括号”的语法！</p>
<p>结合刚刚提到的三点，我们设计一个 DSL 计算器：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">value = <span class="number">0</span></span><br><span class="line"><span class="keyword">def</span> getClear() &#123; value = <span class="number">0</span>&#125;</span><br><span class="line"><span class="keyword">def</span> add(number) &#123; value += number &#125;</span><br><span class="line"><span class="keyword">def</span> getTotal() &#123; println <span class="string">"Total is #value"</span> &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//接下来开始使用这一简介的 DSL</span></span><br><span class="line">clear</span><br><span class="line">add <span class="number">2</span></span><br><span class="line">add <span class="number">5</span></span><br><span class="line">total</span><br></pre></td></tr></table></figure>

<p>由上面的 groovy 创建的简易加法器的 DSL，可以感受到其强大的流畅性。我们在调用时，甚至都可能意识不到这是代码，而是一些配置文件或者普通的文字描述，但这确实是 Groovy 代码。</p>
<p>接下来提供一组这样的数据，进一步解读 DSL。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jump fast,forward turn right move ahead</span><br></pre></td></tr></table></figure>

<p>上面的依旧是 Groovy 代码，首先是 jump 方法的调用，其接受两个参数 fast 和 forward，该方法的返回值类型上有一个 turn 方法，其接受一个 right 参数，同时方法的返回值类型上有一个 move 方法，其接受一个 ahead 参数。这就是 DSL 强大的表现力。其底层就可以用之前讲到的 Groovy 特性提供技术支持。</p>
<h2 id="MOP-与-DSL"><a href="#MOP-与-DSL" class="headerlink" title="MOP 与 DSL"></a>MOP 与 DSL</h2><p>接下来使用 MOP 中的方法合成</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">detailInfo = [:]</span><br><span class="line"><span class="keyword">def</span> methodMissing(String name,args)&#123;</span><br><span class="line">    detailInfo[name] = args</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> introduce(closure)&#123;</span><br><span class="line">    closure.delegate = <span class="keyword">this</span></span><br><span class="line">    closure()</span><br><span class="line">    println <span class="string">"hello,everyone"</span></span><br><span class="line">    detailInfo.each&#123;</span><br><span class="line">        key,value -&gt;</span><br><span class="line">            println <span class="string">"My $key is $value"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">introduce&#123;</span><br><span class="line">    name <span class="string">"zx"</span></span><br><span class="line">    age <span class="number">18</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，利用 Groovy 的 MOP 能力，设计与执行 DSL 将变得非常容易。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/12/13/Groovy与DSL/" title="Groovy与DSL">https://zachaxy.github.io/2017/12/13/Groovy与DSL/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/Groovy/" rel="tag"># Groovy</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/12/12/MOP总结/" rel="next" title="MOP总结">
                <i class="fa fa-chevron-left"></i> MOP总结
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2018/01/03/手写JVM系列-11-线程共享的运行时数据/" rel="prev" title="手写JVM系列(11)-线程共享的运行时数据">
                手写JVM系列(11)-线程共享的运行时数据 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#利用闭包实现上下文相关性"><span class="nav-number">1.</span> <span class="nav-text">利用闭包实现上下文相关性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Groovy-针对流畅性的先天优势"><span class="nav-number">2.</span> <span class="nav-text">Groovy 针对流畅性的先天优势</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#灵活的方法调用语法"><span class="nav-number">2.1.</span> <span class="nav-text">灵活的方法调用语法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#灵活的括号语法"><span class="nav-number">2.2.</span> <span class="nav-text">灵活的括号语法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#让无参数的方法调用也不需要括号"><span class="nav-number">2.3.</span> <span class="nav-text">让无参数的方法调用也不需要括号</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MOP-与-DSL"><span class="nav-number">2.4.</span> <span class="nav-text">MOP 与 DSL</span></a></li></ol></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
